package com.example.ssm1023.exception;

import com.example.ssm1023.config.AppResult;
import com.example.ssm1023.config.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@ControllerAdvice
public class HandlerException {

    /**
     * 处理自定义已知异常
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(ApplicationException.class)
    public AppResult applicationException(ApplicationException e) {
        e.printStackTrace();
        log.error(e.getMessage());
        //获取自己传递的异常信息
        if(e.getErrorResult() != null) {
            return e.getErrorResult();
        }
        //默认异常信息
        return AppResult.fail(e.getMessage());
    }

    /**
     * 处理未捕获的异常
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public AppResult handlerException(Exception e) {
        e.printStackTrace();
        log.error(e.getMessage());
        //非空校验
        if(!StringUtils.hasLength(e.getMessage())) {
            //为空就返回自定义异常
            return AppResult.fail(ResultCode.ERROR_SERVICE);
        }
        //默认的异常信息
        return AppResult.fail(e.getMessage());
    }

}
